#!/usr/bin/python

# makepot.py

# .pot format:
#
#     <whitespace>
#     #. extracted comments (choices)
#     #: file:line
#     msgid "unstranslated_string"
#     msgstr "translated_string"

import sys
import os
import itertools
import operator

from doctest_tools import setpath
Root_dir = setpath.setpath(__file__, remove_first=True)[0]
#print "Root_dir", Root_dir

from naimath.engine import extracted_questions, question
from naimath.lib import po_headers

Translation_dir = os.path.join(Root_dir, 'translation', '0.1', 'po')
#print "Translation_dir", Translation_dir

def write_q_pots():
    for category, questions \
     in itertools.groupby(sorted(extracted_questions.Questions,
                                 key=operator.itemgetter(1)),
                          key=operator.itemgetter(1)):
        write_q_pot(questions, category)

def write_q_pot(questions, category):
    with open(os.path.join(Translation_dir, category + '.pot'), 'w') as f:
        po_headers.write_header(f)
        for q_info in sorted(questions):
            print >> f
            print >> f, "#. type:", q_info[2]
            q_name = q_info[0]
            choices = tuple(q_info[3:])
            print >> f, "#. choices:", ' '.join(c_info[0] for c_info in choices)
            if question.Classes[q_info[2]].translate_choices:
                print >> f, 'msgid "%s"' % (q_name,)
                print >> f, 'msgstr "%s"' % (q_name,)
                for c_info in choices:
                    print >> f
                    for extracted_comment in c_info[2:]:
                        print >> f, "#.", extracted_comment
                    if len(c_info) > 1 and c_info[1]:
                        print >> f, "#:", c_info[1]
                    print >> f, 'msgid "%s:%s"' % (q_name, c_info[0])
                    print >> f, 'msgstr "%s"' % (c_info[0],)
            else:
                for c_info in choices:
                    for extracted_comment in c_info[2:]:
                        print >> f, "#.", c_info[0] + ":", extracted_comment
                refs = itertools.chain.from_iterable(c_info[1].split()
                                                     for c_info in choices
                                                     if len(c_info) > 1)
                print >> f, "#:", ' '.join(sorted(refs, key=ref_key))
                print >> f, 'msgid "%s"' % (q_name,)
                print >> f, 'msgstr "%s"' % (q_name,)

def ref_key(ref):
    file, lineno = ref.split(':')
    return file, int(lineno)

def usage():
    sys.stderr.write("usage: makepot.py\n")
    sys.exit(2)

if __name__ == "__main__":
    if len(sys.argv) != 1: usage()
    write_q_pots()
